package com.ryoma.Utils;


import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class WebConnectorUtils {

    public static String SendGET(String url){
        String result = "";//访问返回结果
        BufferedReader read = null;//读取访问结果

        try {
            URL realurl=new URL(url);
            System.out.println(url);
            URLConnection connection=realurl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            Map<String, List<String>> map = connection.getHeaderFields();

            read = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = read.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(read!=null){
                try {
                    read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("result:【"+result+"】");
        return result;
    }
    /**
     * 向指定URL发送POST请求  很多情况下该方法不够稳定，甚至会出现EOF错误，用下面的getHttpResult 更好一些
     * @param url
     * @param paramMap
     * @return 响应结果
     */
    public static String sendPost(String url, Map<String, String> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());

            String param = "";
            if (paramMap != null && paramMap.size() > 0) {
                Iterator<String> ite = paramMap.keySet().iterator();
                while (ite.hasNext()) {
                    String key = ite.next();// key
                    String value = paramMap.get(key);
                    param += key + "=" + value + "&";
                }
                param = param.substring(0, param.length() - 1);
            }
            out.print(param);
            out.flush();
            in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.err.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("result:【"+result+"】");
        return result;
    }


    public static String getHttpResult(String path, Map<String,String> params) throws  IOException {
        /*0、初始化要发送的数据用list存储*/
        List<NameValuePair> list=new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String,String>  map = iterator.next();
            list.add(new BasicNameValuePair(map.getKey(),map.getValue()));
        }

        HttpPost post=new HttpPost(path);
        HttpClient client=new DefaultHttpClient();

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"utf-8");
        post.setEntity(entity);

        HttpResponse response=client.execute(post);
        if(response.getStatusLine().getStatusCode()==200){
            InputStream in=response.getEntity().getContent();

            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            byte[]arr=new byte [1024];
            int len=0;

            while((len=in.read(arr))!=-1){
                bos.write(arr, 0, len);
            }
            byte[]b=bos.toByteArray();
            return new String(b,0,b.length);
        }
        return null;
    }
}
